package leetcode.code0902;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int atMostNGivenDigitSet(String[] digits, int n) {
		String num = String.valueOf(n);
		int len = num.length();
		int size = digits.length;
		int nums[] = new int[len];
		int ans = 0;
		for (int i = 1; i < nums.length; i++) {
			if (i == 1) {
				nums[i] = size;
			} else {
				nums[i] = nums[i - 1] * size;
			}
			ans += nums[i];
		}
		ans += this.f(0, len, num, true, nums, digits);
		return ans;
	}

	private int f(int index, int range, String num, boolean max, int[] nums, String[] digits) {
		if (index == range) {
			return 1;
		}
		if (!max) {
			return nums[range - index];
		}
		int cur = num.charAt(index) - '0';
		int ans = 0;
		for (int i = 0; i < digits.length; i++) {
			int c = digits[i].charAt(0) - '0';
			if (c < cur) {
				ans += this.f(index + 1, range, num, false, nums, digits);
			} else if (c == cur) {
				ans += this.f(index + 1, range, num, true, nums, digits);
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(20, this.atMostNGivenDigitSet(H.str2array2("[\"1\",\"3\",\"5\",\"7\"]"), 100));
		H.compare(29523, this.atMostNGivenDigitSet(H.str2array2("[\"1\",\"4\",\"9\"]"), 1000000000));
		H.compare(1, this.atMostNGivenDigitSet(H.str2array2("[\"7\"]"), 8));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
